import axios from 'axios'; // 引入axios
import qs from 'qs'; // 引入qs
import Global from './global'; // 引入global.js
import Vue from 'vue';
import {
  Message
} from 'element-ui';
import router from './../router.js'
const projectConfig = require('./../../public/js/config.js');





//登录标识位置
var loginInx = location.href.indexOf('/login?');
//截取参数 , 截取问号后面的字符串
var queryString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1).split('?');
var queryArr = is_empty(queryString[1]) ? '' : queryString[1].split('&');
var queryObj = {};
//参数组合对象
for (let i = queryArr.length - 1; i >= 0; i--) {
  let temp = queryArr[i].split('=');
  queryObj[temp[0]] = temp[1];
}


if (loginInx > -1) {
  //登录token是否空
  if (is_empty(queryObj.token)) {
    queryObj.token = '--';
  }
  localStorage.setItem('logintoken', queryObj.token);
  delete queryObj.token;
}

//设置跳转其他内部平台的地址 例如 后台,个人中心
var redirectUrl = '/login?token=' + queryObj.token;

//请求服务器host字段为空,则使用当前地址的host
if (!is_empty(queryObj.host)) {
  sessionStorage.setItem('host', queryObj.host);
  redirectUrl += '&host=' + queryObj.host;
  delete queryObj.host;
} else if (is_empty(sessionStorage.getItem('host'))) {
  sessionStorage.setItem('host', location.host);
  redirectUrl += '&host=' + location.host;
}

//请求服务器procotol字段为空,则使用当前地址的procotol
if (!is_empty(queryObj.protocol)) {
  sessionStorage.setItem('protocol', queryObj.protocol);
  redirectUrl += '&protocol=' + queryObj.protocol;
  delete queryObj.protocol;
} else if (is_empty(sessionStorage.getItem('protocol'))) {
  sessionStorage.setItem('protocol', location.protocol.replace(':', ''));
  redirectUrl += '&procotol=' + location.protocol.replace(':', '');
}

//设置请求地址
sessionStorage.setItem('host_addr', sessionStorage.getItem('protocol') + '://' + sessionStorage.getItem('host'));
//是否要跳转到后台管理
queryString.indexOf('admin/login') > -1 && sessionStorage.setItem('isAdmin', true);

if (!is_empty(queryObj.ItcJwtToken)) {
  sessionStorage.setItem('ItcJwtToken', queryObj.ItcJwtToken);
  delete queryObj.ItcJwtToken;
}


if (!is_empty(queryObj.CheckSchoolAppCode)) {
  sessionStorage.setItem('CheckSchoolAppCode', queryObj.CheckSchoolAppCode);
  delete queryObj.CheckSchoolAppCode;
}



var ip = sessionStorage.getItem('host').split(":");
sessionStorage.setItem('user_chat_url', 'ws://' + ip[0] + ':7272')

/** 
    PS 登录时必须要携带的参数 token 在登录时有效的参数 CheckSchoolAppCode ItcJwtToken
       其他参数作为跳转到相应模块的参数用paramString来存储,约定 routerUrl 为跳转的路由
*/
//模块字符串
let inx = 0;
var paramString = '';
var moduleString = '';
var urlString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1);
var endInx = urlString.indexOf('?');



//跳转的路由
if (!is_empty(queryObj.routerUrl)) {
  paramString = queryObj.routerUrl;
  // delete queryObj.routerUrl;
}


if (endInx === -1) {
  var urlStringObj = [urlString];
} else {
  var urlStringObj = urlString.substring(0, endInx).split('/');
}


if (is_empty(urlStringObj[0])) {
  moduleString = 'home';
  paramString = '/' + moduleString;

} else if (urlStringObj[0] == 'login') {

  if (is_empty(queryObj.routerUrl)) {
    moduleString = 'home';
    paramString = '/' + moduleString;
  } else {
    moduleString = queryObj.routerUrl.split('/')[0];
    paramString = queryObj.routerUrl;
  }
} else {
  moduleString = urlStringObj[0];
  paramString = '/' + moduleString;
}

sessionStorage.setItem('decisionPlatform', paramString);











//剩下的参数作为跳转的参数
paramString += Object.keys(queryObj).length === 0 ? '' : '?';


Object.keys(queryObj).forEach(function(key) {
  console.log(key, queryObj[key])
  // paramString += (inx === 0 ? '' : '&') + key + '=' + queryObj[key];

  if (key == 'id') {
    paramString += key + '=' + queryObj[key]
  }
  inx++;
})
console.log('paramString====', paramString)
paramString && sessionStorage.setItem('paramString', paramString);
Global.decisionPlatform = sessionStorage.getItem('decisionPlatform') ? sessionStorage.getItem('decisionPlatform') : 'home';



if (process.env.NODE_ENV == 'production') {
  sessionStorage.setItem('host_addr', location.origin);
  // sessionStorage.setItem('wsUrl', 'ws://' + location.host)
  sessionStorage.setItem('wsUrl', (window.location.protocol === 'http:' ? 'ws://' : 'wss://') + location.hostname)
  sessionStorage.setItem('host', location.host)

} else {

  sessionStorage.setItem('host_addr', projectConfig.ServerHost);
  sessionStorage.setItem('wsUrl', projectConfig.WSHost)
  sessionStorage.setItem('host', projectConfig.Serverip)
}


// axios 默认配置  更多配置查看Axios中文文档
axios.defaults.timeout = 60000; // 设置超时值1分钟
// axios.defaults.responseType  = 'json'         // 默认数据响应类型
axios.defaults.withCredentials = true;
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';

// token 过期，取消多条数据请求，放在多个错误弹窗
const CancelToken = axios.CancelToken;
axios.defaults.baseURL = sessionStorage.getItem('host_addr')
// http request 拦截器
// 在ajax发送之前拦截 比如对所有请求统一添加header token
var company = 'BL';
var device_name = 'TE-0600R';
var requestData = null
axios.interceptors.request.use((config) => {
    if (sessionStorage.getItem('PHPSESSID')) {
      config.headers.PHPSESSID = sessionStorage.getItem('PHPSESSID')

    }
    // config.headers.PHPSESSID = cookie.getItem('PHPSESSID')
    // config.cancelToken = cancelSource.token; // 全局添加cancelToken
    // 过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token：
    config.cancelToken = new CancelToken(function executor(c) {
      Global.source = c;
      Global.isCancelSource = c;
    })

    //校验用户登录的 token 的时效性
    const loginTime = localStorage.getItem("loginTime");
    if (loginTime) {

      const newTime = new Date().getTime();
      // 如果大于就是过期了，如果小于或等于就还没过期
      if (newTime - loginTime > Global.EXPIRESTIME) {
        Message.closeAll();
        Message.error("登录已过期，请先登录....");

      }
    }
    // || Global.access_token
    // const DecisionPlatform = config.url.includes('getauth') ? 'cdkey' : 'home'
    if (localStorage.getItem('token')) {

      const DecisionPlatform = config.url.includes('getauth') ? 'cdkey' : 'home'
      const admin = location.pathname.indexOf(Global.isManage) > -1
      // debugger

      config.headers.DecisionPlatform = admin ? 'manage' : DecisionPlatform;
      config.headers.Authorization = `Bearer ${ localStorage.token  || Global.access_token}`;
      config.headers.token = localStorage.getItem('logintoken') == '--' ? null : localStorage.getItem('logintoken');
      config.headers.ItcJwtToken = sessionStorage.getItem('ItcJwtToken');

      let [actioncode, ...actioncodeArr] = config.url.split('/').reverse();
      if (config.method == 'post' || config.method == 'put') {
        if (!config.data.hasOwnProperty('company')) {
          if (config.headers['content-type'] != 'multipart/form-data') {

            //是否字符串，是转换成对象，
            if (Object.prototype.toString.call(config.data) === '[object String]') {
              config.data = qs.parse(config.data);
            }
            //阻止数据结构套娃
            if (config.data.hasOwnProperty('company') && config.data.hasOwnProperty('device_name')) {
              requestData = config.data.data
            } else {
              requestData = config.data;
            }

            delete config.data;
            config.data = {};
            config.data.company = company;
            config.data.device_name = device_name;
            config.data.sign = `${Global.access_token}`;
            config.data.actioncode = config.method + '_' + actioncode;
            config.data.data = requestData;
            config.data = qs.stringify(config.data);
          }
        }

      } else if (config.method == 'get' || config.method == 'delete') {
        // Vue.prototype.cancelRequest()
        // 有些请求没有参数则不传 params，为避免下面添加规范报错，在此同一添加 params
        if (config.params === undefined) {
          config.params = {};
        }

        if (!config.params.hasOwnProperty('company')) {
          requestData = config.params;
          delete config.params;
          config.params = {};
          config.params.company = company;
          config.params.device_name = device_name;
          config.params.sign = `${Global.access_token}`;
          config.params.actioncode = config.method + '_' + actioncode;
          config.params.data = requestData;

        }
      }

    }
    // addPending(config) // 将当前请求添加到 pending 中
    return config;
  },
  err => {
    console.log('err:' + err);
    return Promise.reject(err);
  }
);

// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
axios.interceptors.response.use(function(response) {
  if (process.env.NODE_ENV == 'production') {
    // 打包上线才能获取PHPSESSID
    if (response.config.url.includes('api/system/get_logo')) {
      sessionStorage.setItem('PHPSESSID', response.headers['Set-Cookie'])
    }
  }
  // removePending(response.config) // 在请求结束后，移除本次请求
  // 对响应数据做点什么
  if (!response.config.hasOwnProperty('func')) {
    response.config.func = {};
  }
  if (response.data.hasOwnProperty('data')) {

    var responseData = handleResponseData(response.data, 'need');
  } else {
    var responseData = response.data;
  }


  // 对响应数据做点什么
  Vue.prototype.Ajax_callback(responseData, response.config.func)
  Global.statusCode = 200
  return response;


}, function(error) {

  //超时响应
  if (error.message.indexOf('timeout') > -1) {
    return Vue.prototype.Ajax_callback({
      status: 'timeout',
      msg: '请求超时, 请重新操作。'
    }, error.config.func);
  }

  if (!error.response || !error.config) {
    return
  }

  // removePending(error.config) // 在请求结束后，移除本次请求
  if (error.message.indexOf('终止请求') > -1) {
    return
  }

  if (!navigator.onLine) {
    /*判断网络是否断开*/
    Message.closeAll();
    return Message.error("网络已断开");
  }


  // 对响应错误做点什么
  else if (error.response.status == 401) {

    let config = error.config;
    let actioncodeArr = config.url.split('/');
    Global.statusCode = 401
    get_access_token(function() {
      //重新发送请求，并执行回调
      if (config.method == 'post' || config.method == 'put') {
        config.data = requestData;
        config.data = qs.stringify(config.data);
      }
      if (!config.hasOwnProperty('func')) {
        config.func = {};

      }
      //执行之前的ajax请求
      axios(config).then(response => Vue.prototype.Ajax_callback(response.data, config.func));
    });

  } else if (error.response.status == 505) {

    //2后跳回首页
    Message.closeAll();
    Message.error("请登录");

    setTimeout(() => {
      sessionStorage.clear();
      location.href = location.origin;
    }, 1000)

  } else if (error.response.status == 506) {
    //506说明ItcJwtToken已更改
    let ItcJwtToken = getCookie(itc_jwt_token);
    sessionStorage.setItem('ItcJwtToken', ItcJwtToken);
    setTimeout(() => {
      window.location.reload();
    }, 1500)
  } else if (error.response.status == 606) {
    Global.statusCode = 606
    router.push({
      name: 'cdkey'
    })

  } else if (error.response.status == 707) {
    Message.closeAll();
    Message.error("权限发生改变，请重新登录");
    Global.statusCode = 707

    const success = (res => {})
    const fail = (res => {})
    axios.delete('/api/login/login', {
      params: {},
      func: {
        success,
        fail
      }
    }).then(response => {
      let host_addr = sessionStorage.getItem('host_addr');
      setTimeout(() => {
        sessionStorage.clear();
        localStorage.removeItem("logintoken");
        localStorage.removeItem("token");
        localStorage.removeItem("userid");
        location.href = location.origin;
      }, 1000)
    });
  } else {
    // 对响应数据做点什么
    if (!error.response.config.hasOwnProperty('func')) {
      error.response.config.func = {};
    }
    Vue.prototype.Ajax_callback(error.response.data, error.response.config.func)

  }
  return Promise.reject(error);
});

export default axios; // 这句千万不能漏下！！！

/**
 * 获取access_token 方法封装
 */
function get_access_token(callback) {
  axios.get('/accessToken', {
      params: {
        company: 'BL',
        device_name: 'TE-0600R',
        data: {
          client_id: Global.client_id,
          secret: Global.secret
        }
      }
    })
    .then(response => {

      if (!response) {
        return
      }
      let data = response.data.data;
      Global.access_token = data.access_token;
      localStorage.setItem('token', Global.access_token);
      callback();
    })

}

/**
 * 获取cookie里某个键的值
 */
function getCookie(name) {
  var strcookie = document.cookie; //获取cookie字符串
  conso1e.log('strcookie====', strcookie)
  var arrcookie = strcookie.split("; "); //分割
  //遍历匹配
  for (var i = 0; i < arrcookie.length; i++) {
    var arr = arrcookie[i].split("=");
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return "";
}




/**
 * 清空 pending 中的请求（在路由跳转时调用）
 */
Vue.prototype.clearPending = () => {

  for (const [url, cancel] of pending) {
    cancel(url)
  }
  pending.clear()
}